<?php
header('charset=utf-8');

//if ($_GET['var3'])
//goto boardXML;
// Very important to add this header to ensure the browser reads this file as an XML file 
//header("Content-type: text/xml");
////????????????????????????????????????
//echo '<response><user>Allo</user></response>';
//return;
//$digest = $_SERVER['PHP_AUTH_DIGEST'];
//if (!isset($_SERVER['PHP_AUTH_USER']) ||
//        (($_GET['var1'] != $_SERVER['PHP_AUTH_USER']) && ($_SERVER['PHP_AUTH_USER'] == "root")))
if ((isset($_GET['var1']) &&($_GET['var1'] != $_SERVER['PHP_AUTH_USER']))||(!isset($_GET['var1']) && $_SERVER['PHP_AUTH_USER'] != "root"))
{
     authenticate();
}


$method = $_SERVER['REQUEST_METHOD'];
$userAgent = $_SERVER['HTTP_USER_AGENT'];


// Very important to add this header to ensure the browser reads this file as an XML file 
//????????????????????????????????????
header("Content-type: text/xml");
//????????????????????????????????????

define( "DB_SERVER",    getenv('OPENSHIFT_MYSQL_DB_HOST') );
define( "DB_USER",      getenv('OPENSHIFT_MYSQL_DB_USERNAME') );
define( "DB_PASSWORD",  getenv('OPENSHIFT_MYSQL_DB_PASSWORD') );
define( "DB_DATABASE",  getenv('OPENSHIFT_APP_NAME') );

$database = DB_DATABASE;

mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD) or die('cant connect to database');
mysql_select_db(DB_DATABASE) or die("Unable to select database");

$user = $_GET['var1'];
$collection = $_GET['var2'];
$board = $_GET['var3'];

if ($_SERVER['REQUEST_METHOD'] == 'DELETE')
{

    if (!strstr($userAgent, 'Microchip'))
    {

        //Only Browsers can delete folder
        delete_mysql();
        return;
    } else
    {
        header("HTTP/1.1 404 Bad Request");
        echo $method;
        echo '<record><response>Удаление не поддерживается</response></record>';
        //echo ' DELETE not supported from PIC';
        return;
    }
}
if (($_SERVER['REQUEST_METHOD'] == 'GET'))
{
    $array = array();

    global $user, $collection, $board;

        
    if ($board)
    {
        //header("HTTP/1.1 200 OK  MCHP CLOUD");

        $query = "SELECT * FROM " . $user . " WHERE collection='" . $collection . "' AND board='" . $board . "'";
        $result = mysql_query($query) or die("<response>Ошибка</response>");
        
        $num = mysql_numrows($result);
        if ($num == 0)
        {
            echo '<record>';
            printf("<error>Error no board to display</error>");
            echo '</record>';
            return;
        }

        $i = 0;

        $username = mysql_result($result, $i, "name");
        $collection = mysql_result($result, $i, "collection");
        $board = mysql_result($result, $i, "board");
        $macaddr = mysql_result($result, $i, "macaddr");

        $leds = mysql_result($result, $i, "leds");
        $buttons = mysql_result($result, $i, "buttons");
        $pot = mysql_result($result, $i, "pot");
        $status = mysql_result($result, $i, "status");
        $ledtoggle = mysql_result($result, $i, "ledtoggle");


if (strstr($_SERVER['HTTP_USER_AGENT'], "Microchip"))
        if ($ledtoggle) //Clear the ledtoggle so the PIC doesn't keep toggling his LED
            mysql_query("UPDATE " . $user . " SET ledtoggle=0 " . " WHERE collection='" . $collection . "' AND board='" . $board . "'") or die(mysql_error());

        echo '<record>';
//<username>username</username>
        echo '<username>';
        echo $username;
        echo '</username>';
//<collection>collection</collection>
        echo '<collection>';
        echo $collection;
        echo '</collection>';
//<board>board</board>
        echo '<board>';
        echo $board;
        echo '</board>';
//<macaddr>macaddr</macaddr>
        echo '<macaddr>';
        echo $macaddr;
        echo '</macaddr>';
//<pot>pot</pot>
        echo '<pot>';
        echo $pot;
        echo '</pot>';
//<button>button</button>
        echo '<buttons>';
        echo $buttons;
        echo '</buttons>';
//<leds>leds</leds>
        echo '<leds>';
        echo $leds;
        echo '</leds>';
//<ledtoggle>ledtoggle</ledtoggle>
        echo '<ledtoggle>';
        echo $ledtoggle;
        echo '</ledtoggle>';
//<status>status</status>
        echo '<status>';
        echo $status;
        echo '</status>';

        echo '</record>';
    }else
    if ($collection)
    {
        
        $query = "SELECT * FROM " . $user . " WHERE collection='" . $collection . "'";
        $result = mysql_query($query) or die("<record><fail>Fail</fail></record>");
        $num = mysql_numrows($result);
        if (!$num)
        {
            printf("<record>\n");
            printf("<error>Error no collection to display</error>");
            printf("</record>\n");
            return;
        }
        printf("<record>\n");
        for ($i = 0; $i < $num; $i++)
        {
            $value = mysql_result($result, $i, "board");
            printf("<item>%s</item>\n ", $value);
            //printf("<board%s>%s</board%s>\n ", $i, $value, $i);
        }
        printf("</record>\n");
    } else 
    if ($user)
    {
        
        $query = "SELECT * FROM " . $user;
        $result = mysql_query($query) or die("<record><response>Ошибка</response></record>");
        $num = mysql_numrows($result);
        if (!$num)
        {
            printf("<record>\n");
            printf("<error>Error no collection to display</error>");
            printf("</record>\n");
            return;
        }
        printf("<record>\n");
        for ($i = 0; $i < $num; $i++)
        {
            $value = mysql_result($result, $i, "collection");
            if (!in_array(strtolower($value), $array))
            {
                $array[] = strtolower($value);
                printf("<item>%s</item>\n ", $value);
                //printf("<board%s>%s</board%s>\n ", $i, $value, $i);
            }
        }

        printf("</record>\n");
    }else
    {
        global $database;
        $query = "SHOW TABLES FROM " . $database;
        $result = mysql_query($query) or die("<response>Ошибка</response>");
        printf("<record>\n");
        while ($row = mysql_fetch_row($result))
        {
            printf('<response>'.$row[0].'</response>');
        }
        printf("</record>\n");
        //printf('<record><response>Not inmplemented</response></record>');
    }
}
if ($_SERVER['REQUEST_METHOD'] == 'PUT')
{
    //echo "this is a PUT request\n";
    // Boards does a PUT to update record to the dataBase
    echo '<record>';
    echo '<method>PUT</method>';
    if ($putdata = fopen("php://input", "rb"))
    {
        $xmlfile = "";
        while ($data = fread($putdata, 1024))
        {
            $xmlfile .= $data;
        }
        fclose($putdata);
    } else
    {
        header("HTTP/1.1 500 Internal Server Error");
        echo "** Error opening received file<br>\n";
        return;
    }
    $dom = new DOMDocument;
    $dom->loadXML($xmlfile);

    $user = GetTagValue($dom, 'username');
    echo '<user>'.$user.'</user>';
    $collection = GetTagValue($dom, 'collection');
    echo '<collection>'.$collection.'</collection>';
    $board = GetTagValue($dom, 'board');
    echo '<board>'.$board.'</board>';
    $leds = GetTagValue($dom, 'leds');
    //echo $leds;
    $buttons = GetTagValue($dom, 'buttons');
    //echo $buttons;
    $pot = GetTagValue($dom, 'pot');
    //echo $pot;
    $macaddr = GetTagValue($dom, 'macaddr');
    //echo $macaddr;
    $ledtoggle = GetTagValue($dom, 'ledtoggle');
    //echo $ledtoggle;
    


//    if (($user != "") && ($collection != "") && ($board != "") && ($macaddr != "") && ($leds != "") && ($buttons != "") && ($pot != ""))
    if (($user != "") && ($collection != "") && ($board != ""))
    {
        if ($leds != ""){
            $request = "UPDATE " . $user . " SET leds='" . $leds . "'  WHERE collection='" . $collection . "' AND board='" . $board . "'";
            $status = mysql_query($request) or die(mysql_error());
        }
        if ($buttons != ""){
            $request = "UPDATE " . $user . " SET buttons='" . $buttons . "'  WHERE collection='" . $collection . "' AND board='" . $board . "'";
            mysql_query($request) or die(mysql_error()) or die(mysql_error());
        }
        if ($pot !=""){
            $request = "UPDATE " . $user . " SET pot='" . $pot . "'  WHERE collection='" . $collection . "' AND board='" . $board . "'";
            mysql_query($request) or die(mysql_error());
        }
        if ($macaddr != ""){
            $request = "UPDATE " . $user . " SET macaddr='" . $macaddr . "'  WHERE collection='" . $collection . "' AND board='" . $board . "'";
            mysql_query($request) or die(mysql_error());
        }
        if ($ledtoggle != ""){
            $request = "UPDATE " . $user . " SET ledtoggle='" . $ledtoggle . "'  WHERE collection='" . $collection . "' AND board='" . $board . "'";
            $status = mysql_query($request) or die(mysql_error());
        }
        echo '<response>Успешно</response>';
    }else
    {
        header("HTTP/1.1 401 Bad Request");
        echo '<response>Fail error 401</response>';
    }
    echo '</record>';
    return;
}
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    
    if ($putdata = fopen("php://input", "rb"))
    {
        $xmlfile = "";
        while ($data = fread($putdata, 1024))
        {
            $xmlfile .= $data;
        }
        fclose($putdata);
    } else
    {
        echo '<record>';
        header("HTTP/1.1 500 Internal Server Error");
        echo "** Error opening received file<br>\n";
        echo '</record>';
        return;
    }


    $dom = new DOMDocument;
    $dom->loadXML($xmlfile);
    
    echo '<record>';
    $user = GetTagValue($dom, 'username');
    echo '<user>'.$user.'</user>';
    $collection = GetTagValue($dom, 'collection');
    echo '<collection>'.$collection.'</collection>';
    $passwd = GetTagValue($dom, 'passwd');
    echo '<passwd>'.$passwd.'</passwd>';
    $boardname = GetTagValue($dom, 'boardname');
    echo '<board>'.$board.'</board>';
    
    if ( ($user != "") && ($passwd != "") && ($collection != "") && ($boardname) != "")
    { //Create folder
        Create($user,$passwd,$collection,$boardname);
        echo '<response>Test</response>';
       
    } else
    {
        echo '<response>Не вся информация введена</response>';
        
    }
    echo '</record>';
return;    
}

function delete_mysql()
{
    global $user, $collection, $board;
    //echo 'folder location ' . $user . ' ' . $collection . ' ' . $board . '\n';
    if ($collection == "")
    {
//            $request = "DROP TABLE ".$user;
        $request = "DELETE FROM " . $user;
        //echo $request;
        mysql_query($request);
        echo '<record><response>Успешно</response></record>';
        return;
        
    } else if ($board == "")
    {
        $request = "DELETE FROM " . $user . " WHERE collection='" . $collection . "'";
        //echo $request;
        mysql_query($request);
        echo '<record><response>Успешно</response></record>';
        return;
        
    } else
    {
        $request = "DELETE FROM " . $user . " WHERE collection='" . $collection . "'" . " AND board='" . $board . "'";
        //echo $request;
        mysql_query($request);
        echo '<record><response>Успешно</response></record>';
        return;
    }
}
    function authenticate()
    {
        header('WWW-Authenticate: Basic realm="Basic authentication"');
        header('HTTP/1.1 401 Authorization Required');
        echo "Для доступа к ресурсу требуется ввести правильное имя и пароль\n";
        exit;
    }
function GetTagValue($dom, $Tag)
{
    return $dom->getElementsByTagName($Tag)->item(0)->nodeValue;
}

function Create($user,$passwd,$collection,$boardname)
{


    global $database;
    $query = "SHOW TABLES FROM " . $database;
    $result = mysql_query($query) or die("<response>Fail</response>");
    $userExist = FALSE;

    while ($row = mysql_fetch_row($result))
    {
        if ($row[0] == $user)
            $userExist = TRUE;
    }


    if (!$userExist)
    {
        $file = './.htpassword';
        $fp = fopen($file, "a+");
        if ($fp)
        {
            //Create table "newuser" in My_SQL  in data Base            
            CreateUser($user);
            $un_encryptedUser = '#' . $user . ':' . $passwd . '#';
            fwrite($fp, $un_encryptedUser);
            $encryptedUser = crypt_apr1_md5($user,$passwd);
            fwrite($fp, $encryptedUser);
            fwrite($fp, PHP_EOL);

            fclose($fp);
            //echo "<p>Your Login has been added<p>";
            InsertCollection($user, $passwd, $collection, $boardname);
            echo '<response>Новый пользователь и устройство создано успешно</response>';
            return;
        }else
        {
            echo '<response>Невозможно открыть .htpassword</response>';
            return;
        }
            
    } else
    {

        //User already exist
        $request = "SELECT * FROM " . $user;
        $result = mysql_query($request) or die("<response>Ошибка</response>");
        $password = mysql_result($result, $i, "passwd");
        if (($password != $passwd))
        {
            if ($password !== false)
            {
                echo '<response>Неверный пароль</response>';
                return;
            }
        }

        $request = "SELECT * FROM " . $user . " WHERE collection='" . $collection . "'" . " AND board='" . $boardname . "'";
        $result = mysql_query($request) or die("<response>Ошибка</response>");
        $num = mysql_numrows($result);
        if ($num == 0)
        {
            InsertCollection($user, $passwd, $collection, $boardname);
            echo '<response>Устройство создано успешно</response>';
        } else
        {
            echo '<response>Устройство уже существует</response>';
        }
    }
}
function InsertCollection($name, $passwd, $collection, $board)
{


    $table = $name;

    mysql_query("INSERT INTO $table
                        (name,passwd,collection,board,macaddr,pot,leds,buttons,ledtoggle,status)
                        VALUES
                        ('$name','$passwd','$collection', '$board', 'uninitialized', '512', '85', '5', '0', '0' ) ") or die(mysql_error());
}
function CreateUser($user)
{
    // Create a MySQL table in the selected database
    mysql_query("CREATE TABLE $user(
                            id INT NOT NULL AUTO_INCREMENT, 
                            PRIMARY KEY(id),
                             name VARCHAR(15),
                             passwd VARCHAR(15),
                             collection VARCHAR(15),
                             board VARCHAR(15),
                             macaddr VARCHAR(20),
                             pot  VARCHAR(160),
                             leds  INT,
                             buttons INT,
                             ledtoggle INT,
                             status BOOL)") or die("Already exist");
    //echo "<b>$DataBase</b> created <br>";
    return "<user>".$user . " created</user>";
}
function crypt_apr1_md5($user,$plainpasswd)
{
    $salt = substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 8);
    $len = strlen($plainpasswd);
    $text = $plainpasswd . '$apr1$' . $salt;
    $bin = pack("H32", md5($plainpasswd . $salt . $plainpasswd));
    for ($i = $len; $i > 0; $i -= 16)
    {
        $text .= substr($bin, 0, min(16, $i));
    }
    for ($i = $len; $i > 0; $i >>= 1)
    {
        $text .= ($i & 1) ? chr(0) : $plainpasswd{0};
    }
    $bin = pack("H32", md5($text));
    for ($i = 0; $i < 1000; $i++)
    {
        $new = ($i & 1) ? $plainpasswd : $bin;
        if ($i % 3)
            $new .= $salt;
        if ($i % 7)
            $new .= $plainpasswd;
        $new .= ($i & 1) ? $bin : $plainpasswd;
        $bin = pack("H32", md5($new));
    }
    for ($i = 0; $i < 5; $i++)
    {
        $k = $i + 6;
        $j = $i + 12;
        if ($j == 16)
            $j = 5;
        $tmp = $bin[$i] . $bin[$k] . $bin[$j] . $tmp;
    }
    $tmp = chr(0) . chr(0) . $bin[11] . $tmp;
    $tmp = strtr(strrev(substr(base64_encode($tmp), 2)), "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
    $newUser = "\n" . $user . ":$" . "apr1" . "$" . $salt . "$" . $tmp;
    //printf ($newUser);
    return $newUser;
}

return;
?>

